package com.banciyuan.bcywebview.biz.circles.smooth;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.baidu.mobstat.StatService;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.foldview.FoldLayout;
import com.banciyuan.bcywebview.base.view.tag.TagView;
import com.banciyuan.bcywebview.biz.circles.CircleLikeHelper;
import com.banciyuan.bcywebview.biz.circles.relatedcircle.RelatedCircleActivity;
import com.banciyuan.bcywebview.biz.circles.smooth.fragment.CircleSmoothHotFragment;
import com.banciyuan.bcywebview.biz.circles.smooth.fragment.CircleSmoothPinterestFragment;
import com.banciyuan.bcywebview.biz.circles.smooth.fragment.CircleSmoothTalkFragment;
import com.banciyuan.bcywebview.biz.post.ScreenShots;
import com.banciyuan.bcywebview.biz.post.StartPostActivity;
import com.banciyuan.bcywebview.biz.search.SearchActivity;
import com.banciyuan.bcywebview.biz.share.ShareActivity;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.constants.EventConstants;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.io.Serializable;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.greenrobot.daoexample.model.CircleEnterStatistics;
import de.greenrobot.daoexample.model.DiscoverData;

/**
 * Created by squall on 2016/9/28.
 */
public class CircleTagSmoothActivity extends CircleBaseSmoothActivity implements FoldLayout.OnFoldScrollListener, BaseWatcher {

    private ProgressbarHelper mProgressbarHelper;
    private View mProgressbarView;
    private FoldLayout mFoldLayout;
    private TabLayout mTabLayout;

    private ImageView head_img;
    private ImageView head_back;
    private TextView tvHeadTitle;
    private TextView tvHeadLikeNum;
    private View tvLike;
    private TextView action_title;
    private ImageView mBack;
    private TextView circle_post;
    private ImageView circle_share;
    private ImageView circle_search;
    private TextView ivIntro;
    private View left_block;
    private View viewFocuseBottom;
    private View viewBottomUnfocse;
    private View viewBottomFocsed;
    private TagView relaTags;
    private TextView relaCounts;
    private View infoLine;

    private CircleSmoothPinterestFragment circleSmoothPinterestFragment;
    private CircleSmoothHotFragment circleSmoothHotFragment;
    private CircleSmoothTalkFragment circleSmoothTalkFragment;

    private DiscoverData discoverData;
    private DiscoverData relaData;
    private String[] tabs;

    private boolean isBottomAnimRunning;
    private boolean isRlBottomShowing;

    private boolean isDataEnd;
    private boolean isRelaEnd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_smooth_tag_circle);
        initArgs();
        initProgressbar();
        initUi();
        initAction();
        initCoreStatus();
        initReleProperties();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(CircleTagSmoothActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(CircleTagSmoothActivity.class);
    }

    private void getFragment() {
        circleSmoothPinterestFragment = new CircleSmoothPinterestFragment();
        circleSmoothHotFragment = new CircleSmoothHotFragment();
        circleSmoothTalkFragment = new CircleSmoothTalkFragment();
        setArg();
        flist.add(circleSmoothHotFragment);
        flist.add(circleSmoothPinterestFragment);
        flist.add(circleSmoothTalkFragment);
        setAdapter();
    }

    private void setArg() {
        Bundle index = new Bundle();
        index.putString("id", id);
        index.putString("type", type);
        index.putString("name", name);
        index.putSerializable("rela", relaData);

        Bundle other = new Bundle();
        other.putString("id", id);
        other.putString("type", type);
        other.putString("name", name);

        circleSmoothPinterestFragment.setArguments(index);
        circleSmoothPinterestFragment.passParentScrollY(this);
        circleSmoothHotFragment.setArguments(index);
        circleSmoothHotFragment.passParentScrollY(this);
        circleSmoothTalkFragment.setArguments(other);
        circleSmoothTalkFragment.passParentScrollY(this);
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        super.type = "tag";
        tabs = new String[]{getString(R.string.hot), getString(R.string.newest), getString(R.string.topic)};
    }

    @Override
    protected void initUi() {
        mFoldLayout = (FoldLayout) findViewById(R.id.fold_header);
        mTabLayout = (TabLayout) findViewById(R.id.tablayout);
        circle_post = (TextView) findViewById(R.id.circle_post);
        circle_share = (ImageView) findViewById(R.id.circle_share);
        circle_search = (ImageView) findViewById(R.id.circle_search);

        left_block = findViewById(R.id.left_block);
        left_block.setVisibility(View.GONE);

        action_title = (TextView) findViewById(R.id.base_action_bar_title);
        tvHeadTitle = (TextView) findViewById(R.id.tv_head_title);
        tvHeadLikeNum = (TextView) findViewById(R.id.tv_head_likenum);
        tvLike = findViewById(R.id.circle_focus);
        head_back = (ImageView) findViewById(R.id.iv_acg_bg);
        mPager = (ViewPager) findViewById(R.id.event_content_pager);
        mBack = (ImageView) findViewById(R.id.base_action_bar_home);
        ivIntro = (TextView) findViewById(R.id.intro_tv);
        head_img = (ImageView) findViewById(R.id.circle_header);

        relaTags = (TagView) findViewById(R.id.rela_tags);
        relaCounts = (TextView) findViewById(R.id.rela_count);
        infoLine = findViewById(R.id.info_line);

        initFocuseBottom();
    }

    private void initFocuseBottom() {
        viewFocuseBottom = findViewById(R.id.view_focuse_bottom);
        viewBottomUnfocse = viewFocuseBottom.findViewById(R.id.view_un_focues);
        viewBottomFocsed = viewFocuseBottom.findViewById(R.id.view_focuesed);
        viewBottomUnfocse.setOnClickListener(new OnClick());
        viewFocuseBottom.setVisibility(View.GONE);
    }


    private void setAdapter() {
        mPager.setOffscreenPageLimit(3);
        mPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return flist.get(position);
            }

            @Override
            public int getCount() {
                return flist.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return tabs[position];
            }
        });
        mTabLayout.setupWithViewPager(mPager);
        mPager.setCurrentItem(from);
        if (from > 2) {
            mPager.setCurrentItem(from);
        } else {
            from = "0".equals(discoverData.getTf_status()) ? 0 : 1;
            mPager.setCurrentItem(from);
        }
        switch (from) {
            case 0:
                StatService.onEvent(this, EventConstants.CIRCLE_INDEX, EventConstants.CIRCLE_INDEX);
                break;
            case 1:
                StatService.onEvent(this, EventConstants.CIRCLE_NEWEST, EventConstants.CIRCLE_NEWEST);
                break;
            case 2:
                StatService.onEvent(this, EventConstants.CIRCLE_TALK, EventConstants.CIRCLE_TALK);
                break;
            case 3:
                StatService.onEvent(this, EventConstants.CIRCLE_GOODS, EventConstants.CIRCLE_GOODS);
                break;
        }
    }

    private void initReleProperties() {
        String url = HttpUtils.BASE_URL + TagApi.getRelaProps();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.NAME, name));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    if (StatusCodeUtils.dealStatusCode(s, CircleTagSmoothActivity.this)) {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        String result = jsonObject.getString("data");
                        relaData = gson.fromJson(result, DiscoverData.class);
                        isRelaEnd = true;
                        checkEnd();

                    }
                } catch (Exception e) {
                    isRelaEnd = true;
                    checkEnd();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isRelaEnd = true;
                checkEnd();
            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        mQueue.add(requestParam);
    }

    private void initCoreStatus() {
        String url = HttpUtils.BASE_URL + TagApi.getStatus();
        List<BcyPair> paramsList = new ArrayList<>();
        paramsList.add(new BcyPair(HttpUtils.NAME, name));
        paramsList.add(new BcyPair(HttpUtils.WID, id));
        if (UserDataHelper.ifLogin(this))
            paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        Map<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String result) {
                if (StatusCodeUtils.dealStatusCode(result, CircleTagSmoothActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        Gson gson = new Gson();
                        discoverData = gson.fromJson(jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA).toString(), new TypeToken<DiscoverData>() {
                        }.getType());
                        isDataEnd = true;
                        checkEnd();
                    } catch (Exception e) {
                        isDataEnd = true;
                        checkEnd(false);
                    }
                } else {
                    isDataEnd = true;
                    checkEnd(false);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                isDataEnd = true;
                checkEnd(false);
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, CircleTagSmoothActivity.this, map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        mQueue.add(getUserdataRequest);
    }

    private void checkEnd() {
        checkEnd(true);
    }

    private void checkEnd(boolean flag) {
        if (flag) {
            if (isDataEnd && isRelaEnd) {
                renderAcgItem();
                writeCircleStatistics(discoverData);
                getFragment();
                mProgressbarHelper.onSuccess();
            }
        } else {
            mProgressbarHelper.onFailed();
        }
    }

    private void renderAcgItem() {
        if (relaData != null) {
            int offset = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                offset = UIUtils.dip2px(20, this);
            }
            if (relaData.getRela() != null && !relaData.getRela().isEmpty()) {
                ((View) relaCounts.getParent()).setVisibility(View.VISIBLE);
                relaTags.setTlist(relaData.getRela());
                relaCounts.setText(String.format(getString(R.string.releated_work_pink), String.valueOf(relaData.getRela().size())));
                RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                rl.setMargins(0, UIUtils.dip2px(44, this) + offset, 0, 0);
                infoLine.setLayoutParams(rl);
                ivIntro.setMaxLines(1);
            } else {
                ((View) relaCounts.getParent()).setVisibility(View.GONE);
                RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                rl.setMargins(0, UIUtils.dip2px(54, this) + offset, 0, 0);
                infoLine.setLayoutParams(rl);
                ivIntro.setMaxLines(2);
            }
        }

        if (!TextUtils.isEmpty(discoverData.getCover())) {
            head_img.setDrawingCacheEnabled(true);
            ImageLoader.getInstance().displayImage(discoverData.getCover(), head_img, ImageOptions.options_noneDisplay, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    new AsyncTask<Bitmap, Bitmap, Bitmap>() {
                        @Override
                        protected Bitmap doInBackground(Bitmap... params) {
                            try {
                                ScreenShots screenShots = new ScreenShots(CircleTagSmoothActivity.this);
                                Bitmap bitmap = ImageManager.fastblur(params[0], 20);
                                screenShots.saveBitmap(bitmap, "screencircle.jpg");
                                return bitmap;
                            } catch (Exception e) {
                                return null;
                            }
                        }

                        @Override
                        protected void onPostExecute(Bitmap bitmap) {
                            if (bitmap != null) {
                                head_back.setImageBitmap(bitmap);
                            }
                        }
                    }.execute(view.getDrawingCache());
                }
            });
        }
        if (!TextUtils.isEmpty(discoverData.getName())) {
            tvHeadTitle.setText(discoverData.getName());
            action_title.setText(discoverData.getName());
        }
        if (!TextUtils.isEmpty(discoverData.getIntro())) {
            ivIntro.setText(Html.fromHtml(discoverData.getIntro()));
        }
        doLikeInfoTag();
        mProgressbarHelper.onSuccess();
        SPHelper.putBrowsedCircle(CircleTagSmoothActivity.this, id);
    }

    private void doLikeInfoTag() {
        if ("0".equals(discoverData.getTf_status())) {
            tvLike.setSelected(false);
            tvHeadLikeNum.setText(String.format(getString(R.string.focus_mount_unit), String.valueOf(discoverData.getTf_count())));
        } else {
            tvLike.setSelected(true);
            tvHeadLikeNum.setText(String.format(getString(R.string.focus_mount_unit), String.valueOf(discoverData.getTf_count())));
            viewBottomUnfocse.setVisibility(View.GONE);
            viewBottomFocsed.setVisibility(View.VISIBLE);
            viewBottomFocsed.postDelayed(new Runnable() {
                @Override
                public void run() {
                    hideBottom();
                }
            }, 400);
        }
    }

    @Override
    protected void initAction() {
        mFoldLayout.setOnFoldComplate(new FoldLayout.OnFoldComplate() {
            @Override
            public void folded() {
                action_title.setVisibility(View.VISIBLE);
                tvHeadTitle.setVisibility(View.GONE);
                tvHeadLikeNum.setVisibility(View.GONE);
                left_block.setVisibility(View.VISIBLE);
                if (discoverData != null && discoverData.getTf_status().equals("0")) {
                    viewFocuseBottom.setVisibility(View.VISIBLE);
                    viewBottomUnfocse.setVisibility(View.VISIBLE);
                    viewBottomFocsed.setVisibility(View.GONE);
                    showBottom();
                }
            }

            @Override
            public void unfolder() {
                action_title.setVisibility(View.GONE);
                tvHeadTitle.setVisibility(View.VISIBLE);
                tvHeadLikeNum.setVisibility(View.VISIBLE);
                left_block.setVisibility(View.GONE);
                hideBottom();
            }

            @Override
            public void folding(float percent, int height) {
                float alpha = 1 - percent;
                tvHeadTitle.setAlpha(alpha);
                tvHeadLikeNum.setAlpha(alpha);
                ((View) tvLike.getParent()).setAlpha(alpha);
                ((View) relaCounts.getParent()).setAlpha(alpha);
                ivIntro.setAlpha(alpha);
                head_back.setTranslationY(height / 2);
            }
        });
        OnClick onClick = new OnClick();
        mBack.setOnClickListener(onClick);
        circle_post.setOnClickListener(onClick);
        circle_share.setOnClickListener(onClick);
        circle_search.setOnClickListener(onClick);
        tvLike.setOnClickListener(onClick);
        ivIntro.setOnClickListener(onClick);
        findViewById(R.id.rela_line).setOnClickListener(onClick);

        mTabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mPager) {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                super.onTabSelected(tab);
                switch (tab.getPosition()) {
                    case 0:
                        StatService.onEvent(CircleTagSmoothActivity.this, EventConstants.CIRCLE_TAG_INDEX, EventConstants.CIRCLE_TAG_INDEX);
                        break;
                    case 1:
                        StatService.onEvent(CircleTagSmoothActivity.this, EventConstants.CIRCLE_TAG_NEWEST, EventConstants.CIRCLE_TAG_NEWEST);
                        break;
                    case 2:
                        StatService.onEvent(CircleTagSmoothActivity.this, EventConstants.CIRCLE_TAG_TALK, EventConstants.CIRCLE_TAG_TALK);
                        break;
                }
            }
        });
    }

    protected void showBottom() {
        if (null == viewFocuseBottom || isRlBottomShowing || isBottomAnimRunning)
            return;
        ObjectAnimator.ofFloat(viewFocuseBottom, "translationY", 0)
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = true;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    protected void hideBottom() {
        if (null == viewFocuseBottom || !isRlBottomShowing || isBottomAnimRunning)
            return;
        ObjectAnimator.ofFloat(viewFocuseBottom, "translationY", UIUtils.dip2px(64, this))
                .setDuration(200).start();
        isBottomAnimRunning = true;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRlBottomShowing = false;
                isBottomAnimRunning = false;
            }
        }, 200);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarView = findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initCoreStatus();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    public void onScroll(int Y) {
        mFoldLayout.changeHeader(Y);
        for (int i = 0; i < flist.size(); i++) {
            mFoldLayout.processTransY((FoldLayout.FoldChild) flist.get(i));
        }
    }

    @Override
    public void onTop() {
        tvHeadTitle.setAlpha(1f);
        tvHeadLikeNum.setAlpha(1f);
        ((View) tvLike.getParent()).setAlpha(1f);
        ((View) relaCounts.getParent()).setAlpha(1f);
        ivIntro.setAlpha(1f);
        head_back.setTranslationY(0);
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.CIRCLE_GODISCUSS:
                mPager.setCurrentItem(2);
                break;
            case BaseObserver.CIRCLE_GONEWEST:
                mPager.setCurrentItem(1);
                break;
        }
    }

    private class OnClick implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.base_action_bar_home:
                    finish();
                    break;
                case R.id.circle_focus:
                    if ("0".equals(discoverData.getTf_status())) {
                        doLikeWork("follow");
                    } else {
                        doLikeWork("unfollow");
                    }
                    break;
                case R.id.circle_post:
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            ScreenShots screenShots = new ScreenShots(CircleTagSmoothActivity.this);
                            screenShots.takeShot();
                        }
                    });
                    gotoUtil.gotoAct(CircleTagSmoothActivity.this, StartPostActivity.class, "circle", "", name);
                    overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                    break;
                case R.id.circle_share:
                    goShare();
                    break;
                case R.id.circle_search:
                    goSearch();
                    break;
                case R.id.view_un_focues:
                    doLikeWork("follow");
                    break;
                case R.id.rela_line:
                case R.id.intro_tv:
                    Intent intent = new Intent(CircleTagSmoothActivity.this, RelatedCircleActivity.class);
                    intent.putExtra("relacircle", (Serializable) relaData.getRela());
                    intent.putExtra("discoverdata", discoverData);
                    startActivity(intent);
                    break;
            }
        }
    }

    private void goSearch() {
        gotoUtil.gotoAct(this, SearchActivity.class, "circle", null, discoverData.getName());
    }

    private void goShare() {
        try {
            Intent intent = new Intent(this, ShareActivity.class);
            intent.putExtra("showblock", false);
            intent.putExtra("showDelBtn", false);
            intent.putExtra("showWarnBtn", false);
            intent.putExtra("showCopyLink", true);
            intent.putExtra("showShare", true);
            HashMap<String, String> map = new HashMap<>();
            String strContent = getString(R.string.share_circle);
            String url = String.format(getString(R.string.share_circle_tag_url), discoverData.getName());
            url = encodeUrl(url);
            int count = discoverData.getTf_count();
            map.put("content", String.format(strContent, name, count, url));
            map.put("title", String.format(getString(R.string.share_circle_title), name));
            if (!discoverData.isShow_name())
                map.put("imagePath", discoverData.getCover());
            map.put("url", url);
            intent.putExtra("map", map);
            startActivity(intent);
            overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String encodeUrl(String url) throws Exception {
        Pattern pattern = Pattern.compile("([\\u4e00-\\u9fa5]+)");
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            for (int i = 0; i < matcher.groupCount(); i++) {
                String word = matcher.group(i);
                url = url.replace(word, URLEncoder.encode(word, "UTF-8"));
            }
        }
        return url;
    }


    private void doLikeWork(String type) {
        CircleLikeHelper.doCircleLike(getContext(), discoverData.getTag_id(), "tag", type, new CircleLikeHelper.CircleLikeSuccess() {
            @Override
            public void onCircleLikeSuccess() {
                try {
                    if ("0".equals(discoverData.getTf_status())) {
                        discoverData.setTf_status("1");
                        discoverData.setTf_count(discoverData.getTf_count() + 1);
                    } else {
                        discoverData.setTf_status("0");
                        discoverData.setTf_count(discoverData.getTf_count() - 1);
                    }
                    doLikeInfoTag();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void writeCircleStatistics(final DiscoverData discoverData) {
        if (discoverData == null) return;
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                Gson gson = new Gson();
                String key = SPConstant.CIRCLESTATISTICS + UserDataHelper.getInstance(CircleTagSmoothActivity.this).getUid();
                String data = SPHelper.getString(CircleTagSmoothActivity.this, SPConstant.SPNAME_CIRCLESTATISTICS, key, "[]");
                List<CircleEnterStatistics> clist = gson.fromJson(data, new TypeToken<List<CircleEnterStatistics>>() {
                }.getType());
                if (clist.size() >= 50) {
                    clist.remove(0);
                }
                CircleEnterStatistics circleEnterStatistics = new CircleEnterStatistics(discoverData.getName(), discoverData.getTag_id(), System.currentTimeMillis(), "tag", discoverData.getCover());
                clist.add(circleEnterStatistics);
                SPHelper.putString(CircleTagSmoothActivity.this, SPConstant.SPNAME_CIRCLESTATISTICS, key, gson.toJson(clist));
                return null;
            }
        }.execute();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Intent intent = new Intent(this, CircleTagSmoothActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, id);
        intent.putExtra("from", from);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

    }
}
